package com.baiku.sanhos.controller;

import com.baiku.sanhos.mapper.AppointMapper;
import com.baiku.sanhos.mapper.DeptMapper;
import com.baiku.sanhos.mapper.SourceMapper;
import com.baiku.sanhos.pojo.dto.DeptDTO;
import com.baiku.sanhos.pojo.entity.Dept;
import com.baiku.sanhos.pojo.entity.DoctorAndDept;
import com.baiku.sanhos.pojo.vo.AppointVo;
import com.baiku.sanhos.pojo.vo.DeptVo;
import com.baiku.sanhos.pojo.vo.DoctorIndexVo;
import com.baiku.sanhos.pojo.vo.SourceVo;
import com.baiku.sanhos.response.ResultVO;
import com.baiku.sanhos.response.StatusCode;
import com.baiku.sanhos.utils.RedisKeys;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.*;

@Api(tags = "科室管理")
@RestController
@RequestMapping("/pa/dept")
public class DeptController {
    @Autowired
    Dept dept;
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private AppointMapper appointMapper;

    @Autowired
    private SourceMapper sourceMapper;
    @Autowired
    RedisTemplate<String, DeptVo> redisTemplate;

    //查询科室可以模糊查询
    @ApiOperation("查询科室支持模糊查询")
    @GetMapping("/selectByDeptName/{deptName}")
//    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO selectByDeptName(@PathVariable String deptName) {
        List<DeptVo> list = deptMapper.selectByDeptName(deptName);
        if (list.size() != 0) {
            return ResultVO.ok(list);
        }
        //查询不到数据
        return new ResultVO(StatusCode.DATA_NOT_FOUND);
    }

    @ApiOperation("查询所有科室")
    @GetMapping("")
    //首页页面，不要加权限啦
    public ResultVO selectDept() {
        String key= RedisKeys.REDIS_KEYS_DEPT.getValue();
        ListOperations<String, DeptVo> operations = redisTemplate.opsForList();
        List<DeptVo> list = operations.range(key, 0, -1);
        return ResultVO.ok(list);
    }

    //添加科室
    @ApiOperation("添加科室")
    @PostMapping("/insert")
//    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO insertDept(@RequestBody DeptDTO deptDTO) {
        BeanUtils.copyProperties(deptDTO, dept);
        int status = deptMapper.insert(dept);
        if (status != 0) {
            return ResultVO.ok();
        }
        return new ResultVO(StatusCode.OPERATION_FAILED);
    }

    //修改科室内容
    @ApiOperation("修改科室内容")
    @PutMapping("/updateById")
//    @PreAuthorize("hasAuthority('AAA')")
    public ResultVO updateById(@RequestBody DeptDTO deptDTO) {
        int total = deptMapper.updateByIdDept(deptDTO);
        if (total != 0) {
            return ResultVO.ok();
        }
        return new ResultVO(StatusCode.OPERATION_FAILED);
    }

    //删除科室内容
    @ApiOperation("删除科室内容")
    @DeleteMapping("/deleteById/{id}")
//    @PreAuthorize("hasAuthority('AAA')")
    public ResultVO deleteDept(@PathVariable Integer id) {
        int status = deptMapper.deleteById(id);
        if (status != 0) {
            return ResultVO.ok();
        }
        return new ResultVO(StatusCode.OPERATION_FAILED);
    }

    //根据科室id查询科室信息
    @ApiOperation("根据科室id查询科室信息")
    @GetMapping("/selectByDeptId/{id}")
//    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO selectById(@PathVariable Integer id) {
        DeptVo deptVo = deptMapper.selectById(id);
        if (deptVo != null) {
            return ResultVO.ok(deptVo);
        }
        return new ResultVO(StatusCode.DATA_NOT_FOUND);
    }

    /**
     * 查询每个最高级的科室总共有多少人
     */
    @ApiOperation("查询每个最高级的科室总共有多少人")
    @GetMapping("/getDeptDoctor")
//    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO selectCount() {
        List<DoctorAndDept> list = deptMapper.selectDeptAndDoctorCount();
        return ResultVO.ok(list);
    }

    /**
     * 查询子集科室
     */
    @ApiOperation("查询子集科室")
    @GetMapping("/selectDict")
//    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO selectChild() {
        List<DeptVo> deptVos = deptMapper.selectDict();
        return ResultVO.ok(deptVos);
    }

    /**
     * 渲染前端页面，查询，分页
     *
     * @param page
     * @param pageSize
     * @param deptname
     * @return
     */
    @ApiOperation("渲染前端页面，查询，分页")
    @GetMapping("/selectChild")
//    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO selectChild(@RequestParam("page") int page,
                                @RequestParam("pageSize") int pageSize,
                                @RequestParam("deptname") String deptname) {
        Map<String, Object> map = new HashMap<>();
        int total = deptMapper.getTotalDepts(deptname);//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<DeptVo> depts;
        if (totalPages == 0) {
            depts = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            depts = deptMapper.selectAll(pageSize, offset, deptname);
        }
        map.put("depts", depts);
        map.put("total", total);
        return ResultVO.ok(map);
    }

    /**
     * 根据id实现多删除功能
     *
     * @param ids
     * @return
     */
    @ApiOperation("根据id实现多删除功能")
    @PostMapping("/deleteByIds")
//    @PreAuthorize("hasAuthority('AAA')")
    public ResultVO deleteByIds(@RequestBody List<Integer> ids) {
        deptMapper.deleteByIds(ids);
        return ResultVO.ok();
    }

    /**
     * 渲染科室信息并且分页查询
     *
     * @param page
     * @param pageSize
     * @param deptId
     * @param no
     * @param nickName
     * @return
     */
    @ApiOperation("渲染科室信息并且分页查询")
    @GetMapping("/selectByDeptId")//先传单个参数，后面传对象
//    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO selectByDeptId(@RequestParam("page") int page,
                                   @RequestParam("pageSize") int pageSize,
                                   @RequestParam("deptId") Integer deptId,
                                   @RequestParam("no") String no,
                                   @RequestParam("nickName") String nickName) {
        Map<String, Object> map = new HashMap<>();
        List<DoctorIndexVo> listStatus = deptMapper.selectStatus(deptId);
        for (DoctorIndexVo v : listStatus) {
            if (v.getStatus() == 0) {
                int total = deptMapper.getTotalDoctors(no, nickName, deptId, v.getStatus());//总条数
                int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
                List<DoctorIndexVo> doctorList;
                if (totalPages == 0) {
                    doctorList = new ArrayList<>();
                } else {
                    int offset = (page - 1) * pageSize;
                    doctorList = deptMapper.selectDoctorAll(pageSize, offset, no, nickName, deptId, v.getStatus());
                }
                map.put("doctorList", doctorList);
                map.put("total", total);
            }
        }
        return ResultVO.ok(map);
    }

    /**
     * 渲染号源排班信息并且分页查询
     *
     * @param page
     * @param pageSize
     * @param no
     * @param schedulTime
     * @return
     */
    @ApiOperation("渲染号源排班信息并且分页查询")
    @GetMapping("/selectAppoint")
//    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO selectAppoint(@RequestParam("page") int page,
                                  @RequestParam("pageSize") int pageSize,
                                  @RequestParam("no") String no,
                                  @RequestParam("schedulTime") String schedulTime) {
        Map<String, Object> map = new HashMap<>();
        int total = appointMapper.getTotalDepts(no, schedulTime);//总条数
        int totalPages = (int) Math.ceil((double) total / pageSize);//计算总页数
        List<AppointVo> appointVos;
        if (totalPages == 0) {
            appointVos = new ArrayList<>();
        } else {
            int offset = (page - 1) * pageSize;
            appointVos = appointMapper.selectAll(pageSize, offset, no, schedulTime);
        }
        map.put("deptAppoint", appointVos);
        map.put("total", total);
        return ResultVO.ok(map);
    }

    @ApiOperation("根据科室名称查询科室id")
    @GetMapping("/getDeptIdByDeptName/{deptName}")
    //不要加权限
    public ResultVO selectDeptIdByDeptName(@PathVariable String deptName) {
        int deptId = deptMapper.getDeptIdByDeptName(deptName);
        return ResultVO.ok(deptId);
    }

    /**
     * 科室信息模块
     */

    @GetMapping("/SelectDoctorDept")///pa/dept/SelectDoctorDept
//    @PreAuthorize("hasAuthority('DDD')")
    public ResultVO SelectDoctorDept(@RequestParam("deptname") String deptname,
                                     @RequestParam("page") int page,
                                     @RequestParam("pageSize") int pageSize) {
        /**
         * 科室，通过科室查找
         */
        if (deptname.equals("")) {
            Map<String, Object> map = new HashMap<>();
            int total = deptMapper.getTotalDepts(deptname);//总条数
            int totalPages = (int) Math.ceil((double) total / pageSize);//计算总条数
            List<DeptVo> deptVos;
            if (totalPages == 0) {
                deptVos = new ArrayList<>();
            } else {
                int offset = (page - 1) * pageSize;
                deptVos = deptMapper.selectAll(pageSize, offset, deptname);
            }
            map.put("deptVos", deptVos);
            map.put("total", total);
        }
        List<DeptVo> deptVos = deptMapper.selectByDeptName(deptname);
        if (deptVos.size() == 0) {
            return new ResultVO(1007, "数据不存在");
        }
        return ResultVO.ok(deptVos);
    }
}
